package com.codingman.springjpademo1;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class EmployeeDao {
	@PersistenceContext
	private EntityManager entityManager;

	public void save(Employee e) {
		entityManager.persist(e);
	}

	public void update(Employee e) {
		Employee emp = entityManager.find(Employee.class, e.getId());
		if(emp != null)
		{
			emp.setName(e.getName());
			emp.setSalary(e.getSalary());
		}
		entityManager.merge(emp);
	}

	public void delete(int id) {
		Employee e = entityManager.find(Employee.class, id);
		if(e != null)
			entityManager.remove(e);
	}

	public Employee getEmployeeById(int id) {
		TypedQuery<Employee> query = entityManager.createQuery("select * FROM employee e where e.id = :id", Employee.class);
		query.setParameter("id", id);
		return query.getSingleResult();
	}

	public List<Employee> getAllEmployees() {
		TypedQuery<Employee> query = entityManager.createQuery("SELECT e FROM Employee e", Employee.class);
		return query.getResultList();
	}
}
